package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.dao.PurchaseDetailDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取 新建 或者 被分配的 采购单
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

         wrapper.eq("status", WareConstant.PurchaseStatusEnum.CREATED)
                 .or()
                 .eq("status", WareConstant.PurchaseStatusEnum.ASSIGNED);

         IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();

        // 如果 未指定 合并订单的id 就自动生成一个
        if(purchaseId==null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId=purchaseEntity.getId();
        }



        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().filter((item)->{
            //只有采购选项的状态为 新建 或者 以分配 才能进行合并
            PurchaseDetailEntity entity = purchaseDetailService.getById(item);
            Integer status = entity.getStatus();
            return status==WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()||
                    status==WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode();
        }).map((item) -> {

            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());

        // 进行 订单项合并
        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finalPurchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }


    /**
     * 获取 采购 单
     * @param purChases
     */
    @Transactional
    @Override
    public void acquirePurchases(List<Long> purChases) {

        List<PurchaseEntity> collect = purChases.stream().filter((item) -> {
            PurchaseEntity entity = this.getById(item);
            Integer status = entity.getStatus();
            // 要获取 采购单 必须是 采购单状态为 以分配 时
            return status == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).map((item) -> {
            PurchaseEntity entity = new PurchaseEntity();
            entity.setId(item);
            entity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            entity.setUpdateTime(new Date());
            return entity;
        }).collect(Collectors.toList());

        // 修改 采购单的 状态 以及更新时间
         this.updateBatchById(collect);

         // 修改 采购单关联的 采购项的 状态 为 正在采购
          purchaseDetailService.updateStatusByPurchaseId(collect);

    }

    /**
     *   完成对采购单 的采购
     * @param purchaseDoneVo
     */
    @Transactional
    @Override
    public void receivePurchaseDone(PurchaseDoneVo purchaseDoneVo) {



        boolean flag=true;
        // 对采购 项进行状态 修改
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> update=new ArrayList<>();
        for(PurchaseItemDoneVo vo:items){
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            if(vo.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag=false;
                entity.setStatus(vo.getStatus());
            }else{
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 正常完成 采购订单 就需要入库
                Long detailId = vo.getItemId();
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(detailId);
                wareSkuService.addStock(detailEntity);
            }
              entity.setId(vo.getItemId());
              update.add(entity);
        }
         // 完成对 订单 项的状态 修改
          purchaseDetailService.updateBatchById(update);

      // 对采购单是 状态修改 该状态取决去 采购项 的完成状态
        Long purChaseId = purchaseDoneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purChaseId);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode() :
                WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

}